/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/14 下午5:10
 *
 */


use std::io::Write;
use serde::{Deserialize, Serialize};
use toml::de::Error;
use tracing::info;
use crate::config::info::head::Head;
use crate::config::info::mail::Email;
use crate::config::info::pgsql::Pgsql;
use crate::config::info::redis::Redis;

mod auth;
mod redis;
mod pgsql;
mod head;
pub mod mail;

#[derive(Deserialize,Serialize,Clone)]
pub struct Master{
    pub(crate) head:Head,
    pub(crate) pgsql:Pgsql,
    pub(crate) redis:Redis,
    pub(crate) email:Email
}

impl Master {
    fn init() ->std::io::Result<()>{
        if std::fs::read("./master.toml").is_err(){
            let ns = Self{
                head:Head::default(),
                pgsql:Pgsql::default(),
                redis:Redis::default(),
                email: Default::default(),
            };
            let _ = std::fs::File::create("./master.toml")?
                .write(
                    toml::to_string(&ns).unwrap().as_bytes()
                )?;
        }
        Ok(())
    }
    pub fn new() -> Result<Self, Error>{
        Self::init().unwrap();
        info!("Loading master.toml");
        let ns = std::fs::read("./master.toml").unwrap();
        let ns = std::str::from_utf8(&ns).unwrap().to_string();
        let ns:Self = toml::from_str(ns.as_str())?;
        Ok(ns)
    }
    pub fn local(&self) ->String{
        self.head.format()
    }
    pub fn pgsql(&self) ->String{
        self.pgsql.format()
    }
    pub fn redis_head(&self) ->String{
        self.redis.format()
    }
    pub fn redis_nohead(&self) ->String{
        self.redis.format_nohead()
    }
    pub fn email(&self) ->Email{
        self.email.clone()
    }
}